package com.future.hedongjun.home.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.BasePreference;
import com.future.baselib.utils.DensityUtil;
import com.future.baselib.utils.FlowLayoutManager;
import com.future.baselib.utils.SpaceItemDecoration;
import com.future.hedongjun.R;
import com.future.hedongjun.home.adapter.HistoryAdapter;
import com.future.hedongjun.home.adapter.TopicAdapter;
import com.future.hedongjun.home.bean.TopicBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_clear_history)
    ImageView ivClearHistory;
    @BindView(R.id.recycler_history)
    RecyclerView recyclerHistory;
    @BindView(R.id.layout_history)
    RelativeLayout layoutHistory;
    @BindView(R.id.recycler_search)
    RecyclerView recyclerSearch;
    private HistorySpHelper historySpHelper;
    private HistoryAdapter historyAdapter;
    private TopicAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        setTitle("搜索");
        historySpHelper = new HistorySpHelper(this);
        List<String> history = historySpHelper.getHistory();
        if (history != null && history.size() != 0) {
            layoutHistory.setVisibility(View.VISIBLE);
        } else {
            layoutHistory.setVisibility(View.GONE);
        }
        recyclerHistory.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(this, 10)));
        recyclerHistory.setLayoutManager(new FlowLayoutManager());
        historyAdapter = new HistoryAdapter(history);
        recyclerHistory.setAdapter(historyAdapter);
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                etSearch.setText(historyAdapter.getItem(position));
                search();
            }
        });

        recyclerSearch.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new TopicAdapter(null);
        recyclerSearch.setAdapter(adapter);
        View emptyView = getLayoutInflater().inflate(R.layout.layout_empty_view_default, null);
        TextView tvEmpty = (TextView) emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText("未搜索到课程");
        adapter.setEmptyView(emptyView);

        initSearchEdit();
    }

    private void initSearchEdit() {
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    search();
                    KeyboardUtils.hideSoftInput(textView);
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String txt = editable.toString().trim();
                if (!TextUtils.isEmpty(txt)) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
            }
        });
        KeyboardUtils.showSoftInput(etSearch);
    }

    private void search() {
        String searchTxt = etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(searchTxt)) {
            toast("搜索内容不得为空");
            return;
        }

        historySpHelper.addHistory(searchTxt);

        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode("_searchall_001")
                .addParam("name", searchTxt)
                .addParam("type", 1)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        layoutHistory.setVisibility(View.GONE);
                        recyclerSearch.setVisibility(View.VISIBLE);
                        String info = ((DefaultResponse) response).data;
                        if (TextUtils.isEmpty(info)) {
                            adapter.setNewData(null);
                        } else {
                            List<TopicBean> data = new Gson().fromJson(info
                                    , new TypeToken<List<TopicBean>>() {
                                    }.getType());
                            adapter.setNewData(data);
                        }
                    }
                })
                .start(new DefaultResponse());

    }

    @OnClick({R.id.iv_clear, R.id.iv_clear_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_clear:
                etSearch.setText("");
                break;
            case R.id.iv_clear_history:
                layoutHistory.setVisibility(View.GONE);
                historySpHelper.clearHistory();
                break;
        }
    }

    class HistorySpHelper extends BasePreference {

        private int HistoryLength = 10;
        private String spiltStr = ",";
        private String key = "search_history";

        protected HistorySpHelper(Context context) {
            super(context, "searchHistory");
        }

        public void addHistory(String txt) {
            String searchHistory = getString(key);
//            searchHistory.split(spiltStr)
            if (TextUtils.isEmpty(searchHistory)) {
                searchHistory = txt;
            } else {
                String[] split = searchHistory.split(spiltStr);
                List<String> data = new ArrayList<String>();
                for (int i = 0; i < split.length; i++) {
                    data.add(split[i]);
                }
                if (data.contains(txt)) {
                    data.remove(txt);
                }
                data.add(0, txt);

                if (data.size()>HistoryLength) {
                    data.remove(data.size()-1);
                }

                StringBuilder buffer = new StringBuilder();
                for (String s : data) {
                    buffer.append(s).append(spiltStr);
                }
                searchHistory = buffer.substring(0,buffer.length()-1);
            }
            setString(key, searchHistory);
        }

        public List<String> getHistory() {
            String string = getString(key);
            if (TextUtils.isEmpty(string)) {
                return null;
            }
            String[] split = string.split(spiltStr);
            return Arrays.asList(split);
        }

        public void clearHistory() {
            setString(key, "");
        }

    }
}
